<template>
  <div ref="spriteBox">
    <div ref="sprite" class="sprite"></div>
  </div>
</template>

<script lang="ts">
import {
  computed,
  defineComponent,
  defineEmit,
  PropType,
  reactive,
  ref,
  toRefs,
  watchEffect,
} from "vue";
import { spriteInterface } from "../../interface";
import { useFrameAnimation } from "./useFrameAnimation";

export default defineComponent({
  props: {
    action: {
      type: Boolean,
      default: false,
    },
    spriteObj: Object as PropType<spriteInterface>,
  },
  defineEmit: ["moveEnd"],
  setup(props, { emit }) {
    const spriteBox = ref(null);
    const sprite = ref({ style: "" });
    const spriteObj = reactive(props.spriteObj || {}) as spriteInterface;
    const { width, height, url, length } = toRefs(spriteObj);
    watchEffect(() => {
      if (props.action) {
        useFrameAnimation(
          spriteObj,
          sprite,
          spriteBox,
          () => {
            triggerMove();
          },
          () => {
            emit("moveEnd");
          }
        );
      }
    });
    // 给宽度后边加上单位
    const widthRef = computed(() => {
      return width.value + "px";
    });
    // 给高度后边加上单位
    const heightRef = computed(() => {
      return height.value + "px";
    });
    // 给背景图片连接添加url
    const urlImg = computed(() => {
      return `url("${url.value}")`;
    });
    // 移动到目标位置
    function triggerMove() {
      if (spriteObj.scale || spriteObj.scale === 0) {
        spriteBox.value.style.transform = `scale(${spriteObj.scale})`;
      }
      if (spriteObj.endPosition) {
        Object.keys(spriteObj.endPosition).forEach((o) => {
          if (spriteBox.value && sprite.value.style) {
            spriteBox.value.style[o] = spriteObj.endPosition[o];
          }
        });
      }
    }
    return {
      widthRef,
      heightRef,
      urlImg,
      length,
      sprite,
      spriteBox,
      triggerMove,
    };
  },
});
</script>

<style lang="scss" scoped>
.sprite {
  width: v-bind(widthRef);
  height: v-bind(heightRef);
  background-image: v-bind(urlImg);
  background-repeat: no-repeat;
  background-position: 0;
  background-size: cover;
}
</style>
